# -*- coding: utf-8 -*-
import csv
import sys
import os
import fitz  # PyMuPDF
from pdf2image import convert_from_path
from file_utils import list_files ,calculate_md5,create_folder,get_pdf_page_count

def pdf_to_images(pdf_path, output_folder,output_temp):
    try:
        images = convert_from_path(pdf_path, output_folder=output_temp, poppler_path=r'E:\poppler-23.11.0\Library\bin')  # 替换成你的Poppler路径
        
        for i, image in enumerate(images):
            image_path = f"{output_folder}\page{i + 1}.png"
            image.save(image_path, 'PNG')
            print(f"Page {i + 1} saved as {image_path}")
    except Exception as e:
        sys.stderr.write(str(e))


def newCsv(folder_path):
    file_names = list_files(folder_path)
     # 初始化数据列表
    data = []
    # 初始化表头
    header = ["fileName", "MD5"]
    for file_name in file_names:
        file_item = f"{folder_path}\{file_name}"
        md5 = calculate_md5(file_item)
        print(file_name+":"+md5)
        # temp = os.path.join(output_folder,md5,"temp")
        # image =  os.path.join(output_folder,md5,"image")
        # create_folder(temp)
        # create_folder(image)
        # pdf_to_images(file_item,image,temp)
        row_data = [file_name, md5]
        data.append(row_data)

    csv_file_path = "output.csv"
        # 使用 'w' 模式打开文件，创建 CSV writer 对象
    with open(csv_file_path, 'w', newline='', encoding='utf-8') as csv_file:
        csv_writer = csv.writer(csv_file)

        # 写入表头
        csv_writer.writerow(header)

        # 使用 writerow 写入每一行数据
        for row in data:
            csv_writer.writerow(row)

def jixu(folder_path,csv_file_path):
    with open(csv_file_path, mode='r', encoding='utf-8', newline='') as csv_file:
        # 创建CSV读取对象
        csv_reader = csv.reader(csv_file)
        # 将数据读取为列表
        data_list = list(csv_reader)

    file_names = list_files(folder_path)
    for file_name in file_names:
        file_item = f"{folder_path}\{file_name}"
        md5 = calculate_md5(file_item)
        print(file_name+":"+md5)
        row_data = [file_name, md5]
        data_list.append(row_data)

    # 将更新后的数据写回CSV文件
    with open(csv_file_path, mode='w', encoding='utf-8', newline='') as file:
        # 创建CSV写入对象
        csv_writer = csv.writer(file)

        # 将更新后的数据写回CSV文件
        csv_writer.writerows(data_list)



if __name__ == "__main__":
    # pdf_to_images(sys.argv[1], sys.argv[2],sys.argv[3])   
    pdf_path = r"D:\Users\65720\Desktop\电信项目-方案\文艺\factory\勇罕 2023年 第 2 期.pdf"
    output_folder = r"D:\Users\65720\Desktop\电信项目-方案\文艺\product\iamge"
    output_temp = r"D:\Users\65720\Desktop\电信项目-方案\文艺\product\temp"
    pdf_to_images(pdf_path, output_folder,output_temp)    

    # folder_path = r"D:\Users\65720\Desktop\电信项目-方案\文艺\factory"
    # jixu(folder_path,"output.csv")
   
   
